import React, { Component, Fragment } from "react";
// antd
import { Dropdown, Menu, Table, Button, Col, Pagination, Form, Input, Select, Typography, Space, Tag, Modal, message, Switch, notification } from "antd";
// http
import http from '../../../utils/request';
import Action from "@c/buttonAction/Index";
import { DownOutlined, CheckOutlined, CopyOutlined } from '@ant-design/icons';
import {CopyToClipboard} from 'react-copy-to-clipboard';

// 维护数据
import { maintain_date } from "../../../utils/common";

// import XLSX from "xlsx"
import ExportJsonExcel from "js-export-excel";
import { cmdb_sheet_filter, cmdb_sheet_header, cmdb_sheet_name, pagination_size_option } from "../../../utils/common"

const { TextArea } = Input;
const { Text } = Typography;
const { Option } = Select;


class Slb extends Component {
    constructor(props){
        super(props)
        this.state = {
            loading: false,
            loading_label: false,
            visable_label: false,
            visable_maintain: false,
            visable_label_division: false,
            // 分页
            total: '',
            page: 1,
            page_number: 10,

            // 搜索
            search_instance_platform: null,
            search_instance_account_name: null,
            search_business: null,
            search_division: null,
            search_listener_port: null,
            search_address: null,
            search_instance_id: null,
            search_alarm_status: null,
            search_option_account: [],
            search_option_platform: [],
            
            selectedRowKeys: [],

            // 批量打标签展示
            label_instance_list: null,
            label_list_option: [],
            label_list_option_name: [],

            // 事业部标签
            label_division_list_option: '',
            label_division_list_option_name: '',

            // 维护
            maintain_key: [],
            metric_instance_id: null,
            metric_list_select: [],
            metric_list_column: [{
                key:'metric',
                value: maintain_date
            }],

            // 表格
            dataSource: [],
            columns: [
                {title: "实例ID/名称", dataIndex: "instance_id", key: "instance_id",
                    render: (text, rowData) => {
                        return(
                            <Space direction="vertical">
                                <CopyToClipboard text={rowData.instance_id} 
                                    onCopy={() => 
                                        this.setState({copied: true},
                                        notification.open({
                                            message: '已复制到剪贴板',
                                            icon: <CheckOutlined style={{ color: 'green' }} />,
                                            duration: 2,
                                            placement: 'top',
                                        })
                                    )}
                                >
                                    <span><span style={{marginRight: "5px"}}><CopyOutlined /></span><span style={{color: "#6587FF"}}>{rowData.instance_id}</span></span>
                                </CopyToClipboard>
                                 
                                <Text >{rowData.name}</Text>
                            </Space>
                        )
                    }
                },
                {title: "云平台", dataIndex: "platform", key: "platform",
                    render: (text, rowData) => {
                        return(
                            <div>
                                <Tag color="green">{rowData.platform}</Tag>                                
                            </div>
                        )
                    }
                },
                {title: "云账户", dataIndex: "account_name", key: "account_name",
                    render: (text, rowData) => {
                        return(
                            <div>
                                <Tag color="green">{rowData.account_name}</Tag>                                
                            </div>
                        )
                    }
                },
                {title: "告警", dataIndex: "business", key: "business", width: "160px",
                    render: (text, rowData) => {
                        return(
                            <div>
                                <Tag color="green">{rowData.business}</Tag>
                            </div>
                        )
                    }
                },
                {title: "财务", dataIndex: "division", key: "division", width: "160px",
                    render: (text, rowData) => {
                        return(
                            <div>
                                <Tag color="green">{rowData.division}</Tag>
                            </div>
                        )
                    }
                },
                {title: "项目名", dataIndex: "project_name", key: "project_name"},
                {title: "英文名", dataIndex: "local_name", key: "local_name"},
                {title: "环境", dataIndex: "label_name", key: "label_name"},
                {title: "负责人", dataIndex: "user_name", key: "user_name"},
                {title: "地址", dataIndex: "address", key: "address"},
                {title: '网络', dataIndex: "net_type", key: "net_type"},
                {title: "监听信息", dataIndex: "pay_type", key: "pay_type",
                    render: (text, rowData) => {
                        return(
                            <div>{rowData.listener_protocol}/{rowData.listener_port}</div>
                        )
                    }
                },
                {title: "接警状态", dataIndex: "alarm_status", key: "alarm_status",
                    render: (text, rowData) => {
                        return (
                            <Switch 
                                size="small" 
                                defaultChecked={rowData.alarm_status} 
                                onClick={() => this.onChangeAlarmStatus(rowData.id)} 
                            />
                        )
                    }
                }
            ],
        }
        this.formRefAdd = React.createRef();
        this.formRefLabel = React.createRef();
        this.formRefMaintain = React.createRef();
        this.formRefLabelDivision = React.createRef();
    }

    componentDidMount() {
        this.loadData()
        this.loadDataPlatform()
        this.loadDataBusiness()
        this.loadDataDivision()
    }

    loadDataBusiness = () => {
        const requestDataBusiness = {
            'page': 1,
            'limit': 1000,
        }
        http.get('/business', {params: requestDataBusiness}).then(response=>{
            const resp_data = response.data.data.items
            const label_list_option = []
            const label_list_option_name = []
            for (let i = 0; i < resp_data.length; i++) {
                label_list_option.push(<Option key={resp_data[i].id}>{resp_data[i].name}</Option>)
                label_list_option_name.push(<Option key={resp_data[i].name}>{resp_data[i].name}</Option>)
            }
            label_list_option_name.push(<Option key='none'>空标签</Option>)
            this.setState({
                label_list_option: label_list_option,
                label_list_option_name: label_list_option_name
            })
        })
    }

    loadDataPlatform = () => {
        const requestData = {
            'page': 1,
            'limit': 1000,
        }
        http.get('/cloud/platform', {params: requestData}).then(response=>{
            const search_option_platform = []
            const resp_data = response.data.data.items
            for (let i = 0; i < resp_data.length; i++) {
                search_option_platform.push(<Option key={resp_data[i].name}>{resp_data[i].name}</Option>)
            }
            this.setState({
                search_option_platform: search_option_platform
            })
        })
    }

    loadDataDivision = () => {
        const requestDataBusiness = {
            'page': 1,
            'limit': 1000,
        }
        http.get('/division', {params: requestDataBusiness}).then(response=>{
            const resp_data = response.data.data.items
            const label_division_list_option = []
            const label_division_list_option_name = []
            for (let i = 0; i < resp_data.length; i++) {
                label_division_list_option.push(<Option key={resp_data[i].id}>{resp_data[i].name}</Option>)
                label_division_list_option_name.push(<Option key={resp_data[i].name}>{resp_data[i].name}</Option>)
            }
            label_division_list_option_name.push(<Option key='none'>空标签</Option>)
            this.setState({
                label_division_list_option: label_division_list_option,
                label_division_list_option_name: label_division_list_option_name
            })
        })
    }

    loadData = () => {
        this.setState({
            loading: true
        })
        const requestData = {
            'page': this.state.page,
            'limit': this.state.page_number,
            'platform': this.state.search_instance_platform,
            'account_name': this.state.search_instance_account_name,
            'listener_port__contains': this.state.search_listener_port,
            'instance_id__contains': this.state.search_instance_id,
            'name__contains': this.state.search_instance_name,
            'alarm_status': this.state.search_alarm_status,
            'address__contains': this.state.search_address,
            'business': this.state.search_business,
            'division': this.state.search_division,
        }
    
        // 获取database列表
        http.get('/cloud/slb/listener', {params: requestData}).then(response=>{
            this.setState({
                dataSource: response.data.data.items,
                total: response.data.data.pages.total,
                loading: false
            })
        }).catch()
    }

    // 切换每页数量
    onChangeSizePage = (page, page_number) => {
        this.setState({
            page: page,
            page_number: page_number,
        }, () => {
            this.loadData()
        })
    }

    /** 搜索 */
    onFinishSearch = (data) => {
        this.setState({
            search_instance_platform: data.platform,
            search_instance_account_name: data.account_name,
            search_listener_port: data.listener_port,
            search_address: data.address,
            search_instance_id: data.instance_id,
            search_instance_name: data.name,
            search_alarm_status: data.alarm_status ? data.alarm_status : null,
            search_business: data.search_business ? data.search_business : null,
            search_division: data.search_division ? data.search_division : null,
            page: 1
        })
        this.loadData()
    }

    // 搜索切换云平台
    onChangePlatform = (value) => {
        if (value) {
            this.setState({
                search_instance_platform: value
            })

            const requestData = {
                'page': 1,
                'limit': 1000,
                'platform': value
            }
    
            http.get('/cloud/account', {params: requestData}).then(response=>{
                const search_option_account = []
                const resp_data = response.data.data.items
                for (let i = 0; i < resp_data.length; i++) {
                    search_option_account.push(<Option key={resp_data[i].name}>{resp_data[i].name}</Option>)
                }
                this.setState({
                    search_option_account: search_option_account
                })
            })

        } else {
            this.setState({
                search_option_account: ''
            })
        }
    }

    // 搜索切换云区域
    onChangeRegion = (value) => {
        this.setState({
            search_instance_region: value ? value : null
        })
    }

    // 搜索云账户
    onChangeAccountName = (value) => {
        this.setState({
            search_instance_account_name: value ? value : null
        })
    }

    // 搜索业务线
    onChangeBusiness = (value) => {
        this.setState({
            search_business: value ? value : null
        })
    }

    // 批量选中标签
    onSelectChange = (selectedRowKeys) => {
        this.setState({
            selectedRowKeys: selectedRowKeys
        })
    }


    // 批量打标签按钮
    onLabelBtn = () => {
        if (this.state.selectedRowKeys.length>0) {
            console.log(this.state.selectedRowKeys)
            // 获取列表
            const requestData = {
                instance_id_list: this.state.selectedRowKeys,
                operation_type: 'get_port_list',
            }
            http.patch('/cloud/slb/listener', {params: requestData}).then(response=>{
                const resp_data = response.data.data
                const resp_data_2 = resp_data.join("\n")
                this.setState({
                    label_instance_list: resp_data_2
                })

                this.formRefLabel.current.setFieldsValue({
                    label_instance_list: resp_data_2
                })
            }).catch()

            this.setState({
                visable_label: true,
            })
        } else {
            message.info('请先选中需要打标签的资源实例')
        }
    }

    // 批量打事业部标签
    onLabelDivisionBtn = () => {
        if (this.state.selectedRowKeys.length>0) {
            console.log(this.state.selectedRowKeys)
            // 获取列表
            const requestData = {
                instance_id_list: this.state.selectedRowKeys,
                operation_type: 'get_port_list',
            }
            http.patch('/cloud/slb/listener', {params: requestData}).then(response=>{
                const resp_data = response.data.data
                const resp_data_2 = resp_data.join("\n")
                this.setState({
                    label_instance_list: resp_data_2
                })

                this.formRefLabelDivision.current.setFieldsValue({
                    label_instance_list: resp_data_2
                })
            }).catch()

            this.setState({
                visable_label_division: true,
            })
        } else {
            message.info('请先选中需要打标签的资源实例')
        }
    }

    // 批量打标签任务提交
    onFinishLabel = (data) => {
        this.formRefLabel.current.resetFields()
        this.setState({
            loading_label: true
        })
        const requestData = {
            business_id: data.business_id,
            label_instance_list: data.label_instance_list,
            operation_type: 'change_label',
        }
        http.patch('/cloud/slb/listener', {params: requestData}).then(response=>{
            message.success(response.data.msg)
            this.setState({
                loading_label: false,
                visable_label: false,
                selectedRowKeys: [],
            })
            this.loadData()
        })
    }

    // 批量打标签任务取消
    onFinishLabelCancel = () => {
        this.formRefLabel.current.resetFields()
        this.setState({
            visable_label: false,
            selectedRowKeys: [],
        })
    }

    onChangeAlarmStatus = (id) => {
        const requestData = {
            instance_id: id,
            operation_type: 'change_alarm_status',
        }
        http.patch('/cloud/slb/listener', {params: requestData}).then(response=>{})
    }

    // 维护按钮取消
    onAlarmMaintainCancelBtn = () => {
        this.setState({
            visable_maintain: false,
            metric_list: [],
            metric_list_select: [],
            metric_instance_id: null,
            metric_list_column: [{
                key:'metric',
                value: maintain_date
            }],
        })
        this.formRefMaintain.current.resetFields();
    }

    // 维护列新增
    onAlarmMaintainAddColBtn = () => {
        this.state.metric_list_column.push({
            key:'metric',
            value: maintain_date
        })
        this.setState({
            metric_list_column: this.state.metric_list_column
        })
    }

    // 维护列删除
    onAlarmMaintainDelColBtn = () => {
        this.state.metric_list_column.pop()
        this.setState({
            metric_list_column: this.state.metric_list_column
        })
    }

    // 事业部批量打标签任务取消
    onFinishLabelDivisionCancel = () => {
        this.formRefLabelDivision.current.resetFields()
        this.setState({
            visable_label_division: false,
            selectedRowKeys: [],
        })
    }

    // 批量打标签任务提交
    onFinishLabelDivision = (data) => {
        this.formRefLabelDivision.current.resetFields()
        this.setState({
            loading_label: true
        })
        const requestData = {
            division_id: data.division_id,
            label_instance_list: data.label_instance_list,
            operation_type: 'change_label_division',
        }
        http.patch('/cloud/slb/listener', {params: requestData}).then(response=>{
            this.setState({
                loading_label: false,
                visable_label_division: false,
                selectedRowKeys: [],
            })
            this.loadData()
        })
    }

    // 一键导出
    onexportExcelBtn = () => {
        // 不同云产品添加自定义字段
        const _cmdb_sheet_filter = cmdb_sheet_filter.concat("ip_address", "status", "bandwidth", "instance_type")
        const _cmdb_sheet_header = cmdb_sheet_header.concat('弹性IP', '状态', "带宽", "绑定类型")

        let option = {}
        option.fileName = cmdb_sheet_name
        option.datas = [
            {
                sheetData: this.state.dataSource,
                sheetName: cmdb_sheet_name,
                sheetFilter: _cmdb_sheet_filter,
                sheetHeader: _cmdb_sheet_header
            }
        ]
        var toExcel = new ExportJsonExcel(option)
        toExcel.saveExcel()
    }

    render(){
        const { loading, columns, dataSource, page, total, search_option_platform, search_option_account,
            selectedRowKeys, label_list_option, loading_label, visable_label, label_list_option_name, visable_label_division, 
            label_division_list_option, label_division_list_option_name
        } = this.state
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        }
        const operations = (
            <Menu
                items={[
                    {
                        label: (
                            <Action.Button onClick={() => this.onLabelBtn()}>业务线标签</Action.Button>
                        ),
                        key: '0',
                    },
                    {
                        label: (
                            <Action.Button onClick={() => this.onLabelDivisionBtn()}>事业部标签</Action.Button>
                        ),
                        key: '1',
                    },
                    {
                        label: (
                            <Action.Button onClick={() => this.onexportExcelBtn()} >导出页面数据</Action.Button>
                        ),
                        key: '2',
                    },
                ]}
            />
        );
        var myStyle = {margin: '20px'}
        var myStyle1 = {margin: '15px', float: 'right'}
        var myStyleForm = {marginRight: '10px', marginTop: '5px'}

        return (
            <Fragment>
                <Form layout="inline" onFinish={this.onFinishSearch} size="small">
                    <Form.Item label="实例ID" name="instance_id" style={myStyleForm}>
                        <Input placeholder="实例ID"></Input>
                    </Form.Item>

                    <Form.Item label="实例名称" name="name" style={myStyleForm}>
                        <Input placeholder="实例名称"></Input>
                    </Form.Item>

                    <Form.Item label="监听地址" name="address" style={myStyleForm}>
                        <Input placeholder="监听地址"  />
                    </Form.Item>

                    <Form.Item label="监听端口" name="listener_port" style={myStyleForm}>
                        <Input placeholder="监听端口"  />
                    </Form.Item>

                    <Form.Item label="云平台" name="platform" style={myStyleForm}>
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 200 }}
                            placeholder="请选择云平台"
                            optionFilterProp="children"
                            onChange={this.onChangePlatform}
                            filterOption={(input, option) =>
                            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            {search_option_platform}
                        </Select>
                    </Form.Item>

                    <Form.Item label="云账户" name="account_name" style={myStyleForm}>
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 200 }}
                            placeholder="请选择云账户"
                            onChange={this.onChangeAccountName}
                            >
                            {search_option_account}
                        </Select>                      
                    </Form.Item>

                    <Form.Item label="业务线搜索" name="search_business" style={myStyleForm}>
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 180 }}
                            placeholder="请选择区域"
                            optionFilterProp="children"
                            onChange={this.onChangeBusiness}
                            filterOption={(input, option) =>
                            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            {label_list_option_name}
                        </Select>
                    </Form.Item>

                    <Form.Item label="事业部搜索" name="search_division" style={myStyleForm}>
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 180 }}
                            placeholder="请选择区域"
                            optionFilterProp="children"
                            // onChange={this.onChangeBusiness}
                            filterOption={(input, option) =>
                            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            {label_division_list_option_name}
                        </Select>
                    </Form.Item>

                    <Form.Item label="接警状态" name="alarm_status" style={myStyleForm}>
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 200 }}
                            placeholder="查询接警状态"
                            >
                            <Option key={false}>禁用</Option>
                        </Select>                      
                    </Form.Item>

                    <Form.Item shouldUpdate={true} style={myStyleForm}>
                        <Button type="primary" htmlType="submit">搜索</Button>
                    </Form.Item>
                </Form>

                {/* <div style={myStyle1}><Button type="primary" onClick={() => this.onLabelBtn()} >批量打标签</Button></div> */}
                <div style={myStyle1}>
                    <Dropdown overlay={operations}>
                        <Action.Button>
                            <Space>
                                更多操作
                                <DownOutlined />
                            </Space>
                        </Action.Button>
                    </Dropdown>
                </div>

                <Table
                    size="small"
                    pagination={false} 
                    rowSelection={rowSelection} 
                    rowKey="id" 
                    columns={columns} 
                    dataSource={dataSource}
                    loading={loading}
                    scroll={{ y: 600, x: 1400 }}
                >
                </Table>

                <div style={myStyle}>
                    <Col span={16}>
                        <Pagination
                            onChange={this.onChangeSizePage}
                            current={page}
                            total={total}
                            pageSizeOptions={pagination_size_option}
                            showSizeChanger
                            showQuickJumper
                            showTotal={total => `Total ${total} items`}
                        />
                    </Col>
                </div>

                <Modal
                    title="批量打标签"
                    visible={visable_label}
                    onCancel={this.onFinishLabelCancel}
                    okText="确认"
                    cancelText="取消"
                    footer={null}
                    width="800px"
                >
                    <Form
                        onFinish={this.onFinishLabel}
                        ref={this.formRefLabel}
                        labelCol={{ span: 5 }}
                        wrapperCol={{ span: 14 }}
                    >

                        <Form.Item label="实例列表" name="label_instance_list">
                            <TextArea disabled autoSize={true}></TextArea>
                        </Form.Item>

                        <Form.Item label="业务列表" name="business_id">
                            <Select
                                allowClear
                                showSearch
                                style={{ width: 200 }}
                                placeholder="请选择业务线"
                                optionFilterProp="children"
                                filterOption={(input, option) =>
                                    option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                }
                            >
                                {label_list_option}
                            </Select>
                        </Form.Item>

                        <Form.Item>
                            <Button loading={loading_label} htmlType="submit" type="primary">确定</Button>
                        </Form.Item>                                                               
                    </Form>           
                </Modal>

                <Modal
                    title="批量打标签"
                    visible={visable_label_division}
                    onCancel={this.onFinishLabelDivisionCancel}
                    okText="确认"
                    cancelText="取消"
                    footer={null}
                    width="800px"
                >
                    <Form
                        onFinish={this.onFinishLabelDivision}
                        ref={this.formRefLabelDivision}
                        labelCol={{ span: 5 }}
                        wrapperCol={{ span: 14 }}
                    >

                        <Form.Item label="实例列表" name="label_instance_list">
                            <TextArea disabled autoSize={true}></TextArea>
                        </Form.Item>

                        <Form.Item label="事业部列表" name="division_id">
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 200 }}
                            placeholder="请选择事业部"
                            optionFilterProp="children"
                            filterOption={(input, option) =>
                                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            {label_division_list_option}
                        </Select>
                    </Form.Item>

                        <Form.Item>
                            <Button loading={loading_label} htmlType="submit" type="primary">确定</Button>
                        </Form.Item>                                                               
                    </Form>           
                </Modal>
            </Fragment>
        )
    }
}

export default Slb;
